package com.ng.controller;

import com.ng.common.constant.JwtClaimsConstant;
import com.ng.common.context.BaseContext;
import com.ng.common.properties.JwtProperties;
import com.ng.common.result.PageResult;
import com.ng.common.result.R;
import com.ng.common.utils.JwtUtils;
import com.ng.model.dto.UserDTO;
import com.ng.model.dto.UserLoginDTO;
import com.ng.model.dto.UserPageDTO;
import com.ng.model.po.User;
import com.ng.model.vo.UserLoginVO;
import com.ng.model.vo.UserVO;
import com.ng.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *  不全解释
 *  ----------------------------------------------------------------------------------------------------
 *  丨 注解             丨 支持的类型   丨 支持的请求类型            丨 支持的 Content-Type  丨 请求示例       丨
 *  ----------------------------------------------------------------------------------------------------
 *  丨 @PathVariable   丨 url         丨 GET                     丨 ALL                丨 /test/{id}    丨
 *  ----------------------------------------------------------------------------------------------------
 *  丨 @RequestParam   丨 url         丨 GET                     丨 ALL                丨 /test?id=1    丨
 *  ----------------------------------------------------------------------------------------------------
 *  丨 @RequestBody    丨 body        丨 POST/PUT/DELETE/PATCH   丨 JSON               丨 {“id”:1}      丨
 *  ----------------------------------------------------------------------------------------------------
 */
/**
 * 用户接口 Controller
 *
 * @author Ng
 * @date 2024/03/07
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户", tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public R<UserLoginVO> login(@RequestBody(required = true) UserLoginDTO userLoginDTO) {

        User user = userService.login(userLoginDTO);

        // 登录成功后，生成 JWT 令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUserId());
        // 设置有效期 30 天
        long expireDate = jwtProperties.getUserExpireDate() * 30L;
        String token = JwtUtils.encryptJWT(
                jwtProperties.getUserSecretKey(),
                expireDate,
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .userId(user.getUserId())
                .userName(user.getUserName())
                .name(user.getName())
                .token(token)
                .build();
        return R.success(userLoginVO);
    }

    @ApiOperation("用户登出接口")
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest servletRequest) {

        /**
         * 当前 key = Token 还会有下面这种格式
         * key: Authorization
         * value: Bearer xxxxxx
         */
        // 从请求头中获取 TOKEN
        String token = servletRequest.getHeader(jwtProperties.getUserTokenName());

        // 从 TOKEN 中获取 userId
        Map<String, Object> claims = JwtUtils.decodeJWT(jwtProperties.getUserSecretKey(), token);
        Object userId = claims.get(JwtClaimsConstant.USER_ID);

        if (!userId.toString().isEmpty()) {
            BaseContext.removeCurrentId();
        }

        return R.success();
    }

    @ApiOperation("新增用户接口")
    @PostMapping("/save")
    public R<String> save(@RequestBody UserDTO userDTO) {

        userService.save(userDTO);
        return R.success();
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("/delete")
    public R<String> delete(@RequestParam Long userId) {

        userService.delete(userId);
        return R.success();
    }

    @ApiOperation("编辑用户接口")
    @PutMapping("/update")
    public R<String> update(@RequestBody UserDTO userDTO) {

        userService.update(userDTO);
        return R.success();
    }

    // @PathVariable 占位
    @ApiOperation("启用与禁用用户账号接口")
    @PostMapping("/auth/{status}")
    public R<String> auth(@PathVariable Short status, Long userId) {

        userService.auth(status, userId);
        return R.success();
    }

    @ApiOperation("根据 ID 查询用户接口")
    @GetMapping("/{userId}")
    public R<UserVO> getById(@PathVariable Long userId) {

        User user = userService.getById(userId);

        UserVO userVO = UserVO.builder()
                .userId(user.getUserId())
                .userName(user.getUserName())
                .type(user.getType())
                .name(user.getName())
                .passWord(user.getPassWord())
                .phone(user.getPhone())
                .sex(user.getSex())
                .avatar(user.getAvatar())
                .status(user.getStatus())
                .deleteFlag(user.getDeleteFlag())
                .loginIp(user.getLoginIp())
                .loginTime(user.getLoginTime())
                .pwdUpdateTime(user.getPwdUpdateTime())
                .description(user.getDescription())
                .build();
        return R.success(userVO);
    }

    @ApiOperation("用户分页查询接口")
    @GetMapping("/page")
    public R<PageResult> page(@RequestBody UserPageDTO userPageDTO) {

        PageResult pageResult = userService.pageQuery(userPageDTO);
        return R.success(pageResult);
    }

    @ApiOperation("查询指定时间段内创建用户接口")
    @PostMapping("/count")
    public R<Map<String, Integer>> countByUserId(@RequestBody Map map) {

        Integer count = userService.countByUserId(map);
        Map<String, Integer> resMap = new HashMap<>();
        resMap.put("count", count);

        return R.success(resMap);
    }
}
